package com.corp.common.base.util;

import com.corp.common.base.constant.SystemConstant;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;

import java.nio.charset.Charset;

/**
 * @author Keanu
 * @version 1.0 2019/7/25 0025
 */
public class DigestUtils {

    public static final Charset UTF_8 = Charset.forName(SystemConstant.UTF_8);


    public static String base64(String text) {
        return base64(text.getBytes(UTF_8));
    }

    public static String base64(byte[] bytes) {
        return new String(Base64.encodeBase64(bytes), UTF_8);
    }

    public static byte[] decodeBase64(String base64Text) {
        return decodeBase64(base64Text.getBytes(UTF_8));
    }

    public static byte[] decodeBase64(byte[] base64Bytes) {
        return Base64.decodeBase64(base64Bytes);
    }

    public static String base64URLSafe(byte[] bytes) {
        return new String(Base64.encodeBase64URLSafe(bytes), UTF_8);
    }

    // provide wrapper of common codec for convenience

    public static String md5(String text, String salt) {
        if (StringUtils.isNotBlank(salt)) {
            text += salt;
        }
        return md5(text.getBytes(UTF_8));
    }

    public static String md5(byte[] bytes) {
        return org.apache.commons.codec.digest.DigestUtils.md5Hex(bytes);
    }

    public static String hex(byte[] bytes) {
        return new String(Hex.encodeHex(bytes));
    }

    public static byte[] decodeHex(String text) {
        try {
            return Hex.decodeHex(text.toCharArray());
        } catch (DecoderException e) {
            throw new IllegalArgumentException(e);
        }
    }

    public static String sha512(String text) {
        return org.apache.commons.codec.digest.DigestUtils.sha512Hex(text);
    }

    public static byte[] sha512(byte[] text) {
        return org.apache.commons.codec.digest.DigestUtils.sha512(text);
    }

    private DigestUtils() {
    }
}
